<?php

namespace catchAdmin\model;

use catcher\exceptions\AlertErrorException;

class WechatUserBalance extends ModelApp
{

    protected $append = [
        'balance_type_name',
        'balance_type_2_name',
        'balance_status_name',
        'balance_status_time_show',
        'created_at_show',
    ];


    ################################### 关系 start ###########################

    public function wechatUser()
    {
        return $this
            ->hasOne(WechatUser::class, 'id', 'wechat_user_id')
            ->bind([
                'wechat_user_phone'        => 'phone',
                'wechat_user_nickname'     => 'nickname',
                'wechat_user_company_name' => 'company_name',
            ]);
    }

    ################################### 关系 end ###########################
    ################################### Attr start ###########################

    /**
     * created_at_show
     */
    public function getCreatedAtShowAttr()
    {
        return date('m月d日 H:i', $this->getOrigin('created_at'));
    }


    /**
     * balance_status_time_show
     */
    public function getBalanceStatusTimeShowAttr()
    {
        if (empty($this->getOrigin('balance_status_time'))) {
            return "";
        }

        return date('Y-m-d H:i', $this->getOrigin('balance_status_time'));
    }


    /**
     * balance_type_name_list
     */
    public function getBalanceTypeNameList()
    {
        return [
            1 => '余额',
            2 => '积分',
            3 => '收益',
        ];
    }


    public function getBalanceType2NameBalanceList()
    {
        return [
            '101' => '充值',
            '102' => '充值赠送',
            '103' => '需求支付消费',
        ];
    }


    public function getBalanceType2NameJiFenList()
    {
        return [
            '201' => '充值',
        ];
    }


    public function getBalanceType2NameIncomeList()
    {
        return [
            '301' => '佣金收入',
            '302' => '提现',
            '303' => '提现未通过',
        ];
    }


    public function getBalanceStatusNameList()
    {
        return [
            '1' => '审核中',
            '2' => '通过',
            '3' => '未通过',
        ];
    }


    /**
     * balance_status_name
     */
    public function getBalanceStatusNameAttr()
    {
        return $this->getBalanceStatusNameList()[$this->getOrigin('balance_status')] ?? '';
    }


    /**
     * balance_type_2_name
     */
    public function getBalanceType2NameAttr()
    {
        $list = [];
        // 余额
        foreach ($this->getBalanceType2NameBalanceList() as $k => $v) {
            $list[$k] = $v;
        }
        // 积分
        foreach ($this->getBalanceType2NameJiFenList() as $k => $v) {
            $list[$k] = $v;
        }
        // 收入
        foreach ($this->getBalanceType2NameIncomeList() as $k => $v) {
            $list[$k] = $v;
        }

        return $list[$this->getOrigin('balance_type_2')] ?? '';
    }


    /**
     * balance_type_name
     */
    public function getBalanceTypeNameAttr()
    {
        return $this->getBalanceTypeNameList()[$this->getOrigin('balance_type')] ?? '';
    }


    /**
     * num
     */
    public function getNumAttr()
    {
        return abs($this->getOrigin('num'));
    }

    ################################### Attr end ###########################
    ############################ search start ###############################

    public function searchBalanceTypeAttr($query, $value, $data)
    {
        $query->where('balance_type', $value);
    }


    public function searchBalanceStatusAttr($query, $value, $data)
    {
        $query->where('balance_status', $value);
    }


    /**
     * time_type
     */
    public function searchTimeTypeAttr($query, $value, $data)
    {
        $from = 0;
        $to = strtotime(date("Y-m-d 23:59:59"));

        if ($value == "today") {
            $from = strtotime(date("Y-m-d 00:00:00"));
            $to = strtotime(date("Y-m-d 23:59:59"));
        } elseif ($value == "yesterday") {
            $from = strtotime(date("Y-m-d 00:00:00", strtotime('-1 day')));
            $to = strtotime(date("Y-m-d 23:59:59", strtotime('-1 day')));
        } elseif ($value == "this_month") {
            $from = strtotime(date("Y-m-01 00:00:00"));
            $to = strtotime(date("Y-m-d 23:59:59"));
        }

        $query->whereBetween('created_at', [$from, $to]);
    }


    public function searchBalanceType2Attr($query, $value, $data)
    {
        $query->where('balance_type_2', $value);
    }


    public function searchWechatUserCompanyNameAttr($query, $value, $data)
    {
        $query
            ->join('wechat_user', 'wechat_user.id = wechat_user_balance.wechat_user_id', 'INNER')
            ->where('wechat_user.company_name', 'like', '%' . $value . '%');
    }


    ############################ search end ###############################
    ################################### func start ###########################

    public function getRechargeBalanceConfig($id)
    {
        $msg = [];

        foreach ($this->getRechargeBalanceList() as $k => $v) {
            if ($id == $v['id']) {
                $msg = $v;
                break;
            }
        }

        return $msg;
    }


    public function getRechargeBalanceList()
    {
        $list = (new SysRecharge())
            ->order('value', 'asc')
            ->select()
            ->toArray();

        $list_2 = [];
        foreach ($list as $k => $v) {
            $v['selected'] = false;

            $list_2[$k] = $v;
        };

        return $list_2;
    }


    public function saveWechatUserBalance($param)
    {
        $wechat_user = (new WechatUser())
            ->where('id', $param['wechat_user_id'])
            ->find();

        if ($param['num'] <= 0) {
            throw new AlertErrorException();
        }

        // 1.用户余额
        {
            if ($param['balance_type'] == 1) {
                $from = $wechat_user->balance;

                // 101=充值，102=充值赠送
                if ($param['balance_type_2'] == 101
                    || $param['balance_type_2'] == 102) {
                    $direction = "+";
                    $to = mathJia($from, $param['num']);
                } elseif ($param['balance_type_2'] == 103) {
                    $direction = "-";
                    $to = mathJian($from, $param['num']);
                } else {
                    throw new AlertErrorException();
                }

                $wechat_user->balance = $to;

                if ($wechat_user->balance < 0) {
                    throw new AlertErrorException('余额不能小于0');
                }
                // 2.积分
            } elseif ($param['balance_type'] == 2) {
                $from = $wechat_user->ji_fen;

                // 201=积分充值
                if ($param['balance_type_2'] == 201) {
                    $direction = "+";
                    $to = mathJia($from, $param['num']);
                } else {
                    throw new AlertErrorException();
                }

                $wechat_user->ji_fen = $to;

                if ($wechat_user->ji_fen < 0) {
                    throw new AlertErrorException('积分不能小于0');
                }
                // 3.收入
            } elseif ($param['balance_type'] == 3) {
                $from = $wechat_user->income;

                // 301=佣金收入
                if ($param['balance_type_2'] == 301
                    || $param['balance_type_2'] == 303) {
                    $direction = "+";
                    $to = mathJia($from, $param['num']);
                    // 302=提现
                } elseif ($param['balance_type_2'] == 302) {
                    $direction = "-";
                    $to = mathJian($from, $param['num']);
                } else {
                    throw new AlertErrorException();
                }

                $wechat_user->income = $to;

                if ($wechat_user->income < 0) {
                    if ($param['balance_type_2'] == 302) {
                        throw new AlertErrorException('提现金额过多');
                    }
                    throw new AlertErrorException('收入不能小于0');
                }
            } else {
                throw new AlertErrorException();
            }

            // 保存
            $wechat_user->save();
        }

        // 2.日志
        return $this->saveDataCC([
            'wechat_user_id' => $param['wechat_user_id'],
            'from'           => $from,
            'to'             => $to,
            'direction'      => $direction,
            'num'            => $param['num'],
            'balance_type'   => $param['balance_type'],
            'balance_type_2' => $param['balance_type_2'],
            'out_trade_no'   => $param['out_trade_no'] ?? '',

            'balance_status'         => $param['balance_status'] ?? 0,
            'wechat_user_payment_id' => $param['wechat_user_payment_id'] ?? 0,

            // 提现信息
            'wechat_user_bank_id'    => $param['wechat_user_bank_id'] ?? 0,
            'bank_name'              => $param['bank_name'] ?? '',
            'bank_kai_name'          => $param['bank_kai_name'] ?? '',
            'bank_no'                => $param['bank_no'] ?? '',
        ]);
    }

    ################################### func end ###########################

}
